/******************************************************************************
 * Copyright (C) 671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NET_INCLUDE_NODECPP_NET_TCPSERVER_H_
#define NET_INCLUDE_NODECPP_NET_TCPSERVER_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <boost/unordered_map.hpp>
#include <NodeCpp/Macros.h>
#include <NodeCpp/AtomicValue.h>
#include <NodeCpp/ScopedPtr.h>
#include <NodeCpp/ScopedArray.h>
#include <NodeCpp/Runnable.h>
#include <NodeCpp/Mutex.h>
#include <NodeCpp/ThreadPool.h>
#include <NodeCpp/Net/TcpAcceptor.h>

namespace NodeCpp {
namespace Net {
	class TcpSocket;
    class TcpSocketDelegateFactory;

    class TcpRunnable : public Runnable
    {
    public:
        TcpRunnable(void);
        virtual ~TcpRunnable(void);

        bool Init(void);
        void Stop(void);

        struct event_base* AcquireBase(void) {
            ++Load_;
            return Base_;
        }
        void ReleaseBase(void) { --Load_; }
        std::uint32_t GetLoad(void) const { return Load_; }

        virtual void Run(void);

    private:
        void _Uninitialize(void);
		static void _OnTimeout(evutil_socket_t, short, void *);

        struct event_base *Base_;
        struct event *DummyEvent_;
        AtomicValue_UInt32 Load_;
        DISALLOW_COPY_AND_ASSIGN(TcpRunnable);
    };

    class TcpServer
    {
    public:
        /* Max worker number */
        const static int MAX_WORKERS = 0x80;

        TcpServer(TcpSocketDelegateFactory *_ConnFactory = NULL);
        ~TcpServer(void);

        void SetConnectionFactory(TcpSocketDelegateFactory *_ConnFactory);
        bool SetThreadPool(ThreadPool* _ThreadPool, Thread::Priority _Priority = Thread::PRIO_NORMAL);
        ThreadPool* GetThreadPool(void) const { return RunnerPool_; }

        /* Start server */
        bool Start(const char *_Host, int _Port, int _Backlog, int _AddWorkerNum = 0);
        /* Stop server */
        void Stop(void);
        /* Close listener */
        void CloseListener(void) { Acceptor_->Close(); }
        /* Get error code */
        int GetErrorCode(void) const { return ErrorCode_; }
        /* Get error description */
        const std::string& GetErrorString(void) const { return ErrorString_; }
        bool IsRunning(void) const { return Running_; }

    private:
        friend class TcpSocket;

        void _Uninitialize(void);
        void _GenErrorInfo(void);
        void _CloseSocket(TcpSocket *_Sock);
        bool _CreateAddtionalWorkers(int _AddWorkerNum);
        void _StopAddtionalWorkers(void);
        void _CloseAddtionalWorkers(void);
		void _DoAccept(evutil_socket_t, struct sockaddr *, int, void *);
        bool _StartRunner(void);
        TcpRunnable *_FindWorker(void);

		static void _OnAccept(evutil_socket_t, struct sockaddr *, int, void *);

        ScopedPtr<TcpAcceptor> Acceptor_;
        typedef boost::unordered_map<int, TcpSocket*>   SocketMap;
        volatile int ConnIDGen_;
        SocketMap Connections_;
        Mutex ConnectionsLock_;
        ScopedPtr<TcpSocketDelegateFactory> Connf_;
        TcpRunnable MainWorker_;
        std::size_t AddtionalWorkerNum_;
        ScopedArray<TcpRunnable*> AddtionalWorkers_;
        int ErrorCode_;
        std::string ErrorString_;
        ThreadPool* RunnerPool_;
        Thread::Priority RunnerPriority_;
        volatile bool Running_;
        DISALLOW_COPY_AND_ASSIGN(TcpServer);
    };

}}

#endif // NET_INCLUDE_NODECPP_NET_TCPSERVER_H_
